package com.maxjay.component.metadata.core;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.maxjay.common.util.cache.CacheUtil;
import com.maxjay.component.metadata.core.parser.EntityParser;
import com.maxjay.component.metadata.model.Entity;
import com.maxjay.system.core.spring.BeanContext;

public class EntityFactoryImpl implements EntityFactory {
	
	private static final Logger LOG = Logger.getLogger(EntityFactoryImpl.class);
	
	protected static final String ENTITY_CACHE_KEY = "entityCache";
	
	private static final String ENTITY_PARSER_KEY = "entityParser";
	
	protected Cache entityCache = null;
	
	protected BeanContext beanContext;
	
	public EntityFactoryImpl() {
	}
	
	public EntityFactoryImpl(BeanContext beanContext) {
		this.beanContext = beanContext;
		entityCache = CacheUtil.getManager().getCache(ENTITY_CACHE_KEY);
	}

	public Entity getEntity(String entityId) {
		if(StringUtils.isBlank(entityId)) {
			throw new RuntimeException("实体对象ID为空，请传入entityId参数");
		}
		Entity entity = null;
		Element element = entityCache.get(entityId);
		if(element == null){
			LOG.info("缓存中没有实体[" + entityId + "]，系统重新加载...");
			entity = loadEntity(entityId);
		}else{
			entity = (Entity)element.getValue();
		}
		return entity;
	}
	
	public Entity loadEntity(String entityId) {
		entityCache.remove(entityId);
		LOG.info("加载实体[" + entityId + "]");
		EntityParser entityParser = beanContext.getBean(ENTITY_PARSER_KEY, EntityParser.class);
		Entity entity = entityParser.parseEntity(entityId);
		entityCache.put(new Element(entityId, entity));
		return entity;
	}
	
	public boolean isLoadedEntity(String entityId) {
		Element element = entityCache.get(entityId);
		if(element == null) {
			return false;
		} else {
			return true;
		}
	}
	
	public void destroy() {
		LOG.info("销毁实体缓存成功...");
		entityCache.dispose();
	}

	@Override
	public void reloadAll() {
		LOG.info("清除实体缓存成功...");
		entityCache.removeAll();
	}

}
